<template>
    <div class="page-container">
        <div class="tool-box">
            <SelectTrigger label="加载模型的方式：" :options="options" />
            <SelectTrigger label="光照：" :options="options1" />
            <SelectTrigger label="3DTile贴图：" :options="options2" />
        </div>
        <div id="cesiumContainer"></div>
    </div>
</template>
<script setup>
import * as Cesium from 'cesium';
import TOKEN from '@/utils/cesium/token.js';
const options = ref([]); // 模型选项
const options1 = ref([]); // 光照
const options2 = ref([]); // 3DTIles 贴图

let viewer;

onMounted(async () => {
    Cesium.Ion.defaultAccessToken = TOKEN;
    // 实例化
    viewer = new Cesium.Viewer('cesiumContainer', {
        infoBox: false,
        selectionIndicator: false, //
        shadows: true,
        shouldAnimate: true,
        // contextOptions: {
        //     // 开启MSAA抗锯齿（多重采样）
        //     msaaSamples: 4, // 可选值：2, 4, 8（值越高效果越好但性能消耗越大）
        // },
        // resolutionScale: 1.5, // 渲染分辨率为屏幕的1.5倍
    });
    // const fxaa = Cesium.PostProcessStageLibrary.createFXAAStage();
    // viewer.scene.postProcessStages.add(fxaa);

    viewer.camera.flyTo({
        duration: 1.5,
        destination: Cesium.Cartesian3.fromDegrees(114.2576, 30.55333, 8000),
    });

    // loadGltf();
    loadLight();
    loadLayer();
    load3DTiles();
});

function loadGltf() {
    options.value = [
        {
            text: '加载output.gltf',
            onselect: function () {
                loadLocalModel1('/src/assets/model/output.gltf', 0.0);
            },
        },
        {
            text: '加载untitled.glb',
            onselect: function () {
                loadLocalModel('/src/assets/model/untitled.glb', 0.0);
            },
        },

        {
            text: '加载 model.glb',
            onselect: function () {
                loadLocalModel('/src/assets/model/model.glb', 5000.0);
            },
        },
        {
            text: '加载 MetalRoughSpheres.gltf',
            onselect: function () {
                loadLocalModel('/src/assets/model/MetalRoughSpheres.gltf', 5000.0);
            },
        },
        {
            text: '加载 newmodel.glb',
            onselect: function () {
                loadLocalModel('/src/assets/model/newmodel.glb', 5000.0);
            },
        },

        {
            text: '加载 PSFS.glb',
            onselect: function () {
                loadLocalModel('/src/assets/model/PSFS.glb', 50.0);
            },
        },
    ];
}

// 支持模型格式： COLLADA、gITF、OBJ
//  加载本地模型
function loadLocalModel(url, height) {
    // 创建自定义着色器
    // 适配更多Cesium版本的自定义着色器
    const customShader = new Cesium.CustomShader({
        lightingModel: Cesium.LightingModel.PBR,
        translucent: true, // 默认为 false，开启后 alpha 才生效
        fragmentShaderText: `
        void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
          // 设置基础颜色

        //   material.diffuse = vec3(0.0392, 0.2196, 0.5686);
          material.metallic = 0.8;      // 类似于金属度
          material.roughness = 0.3;     // 类似于粗糙度的倒数

        //   material.specular = 0.8;      // 类似于金属度
        //  material.shininess = 0.3;     // 类似于粗糙度的倒数


          // material.emissive = vec3(0.05, 0.05, 0.1);

        }
      `,
    });
    viewer.entities.removeAll();
    const position = Cesium.Cartesian3.fromDegrees(114.29037269789845, 30.54794349909054, height);
    const heading = Cesium.Math.toRadians(0);
    const pitch = 0;
    const roll = 0;
    const hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
    // 方位
    const orientation = Cesium.Transforms.headingPitchRollQuaternion(position, hpr);
    const entity = viewer.entities.add({
        name: url,
        position: position, // 位置
        orientation: orientation,
        model: {
            uri: url,
            // minimumPixelSize: 128, // 用于指定模型的最小像素大小，而不考虑缩放
            maximumScale: 20000, // 模型的最大比例尺大小。 最小像素大小的上限
            scale: 1.0, // 添加缩放属性
            // customShader: customShader,
        },
    });

    console.log('entity', entity.model);
    viewer.trackedEntity = entity; // 相机聚焦实体
}

// 支持模型格式： COLLADA、gITF、OBJ
//  加载本地模型
async function loadLocalModel1(gltfUrl, height) {
    // 使用fromGltfAsync加载模型（推荐的异步API）
    const gltfJson = await Cesium.Resource.fetchJson(gltfUrl);
    console.log('gltfJson', gltfJson);
    const gltfModel = await Cesium.Model.fromGltfAsync({
        url: gltfUrl,
        // 模型初始位置（临时，后续会根据nodes调整）
        modelMatrix: Cesium.Transforms.eastNorthUpToFixedFrame(
            Cesium.Cartesian3.fromDegrees(114.2576, 30.55333, 0) // 初始参考点（如北京）
        ),
    });
    viewer.scene.primitives.add(gltfModel);

    gltfModel.readyEvent.addEventListener(() => {
        console.log('gltfModel', gltfModel.loader.components);

        // const nodeModel = gltfModel.getNode('武汉市武东医院'); // 替换为实际节点名称
        // console.log('model.nodeHierarchy', gltfModel.nodeHierarchy);
    });
    // console.log('gltfModel', gltfModel);
    // gltfJson.nodes.forEach(nodeData => {
    //     console.log('nodeData',nodeData)

    //     // console.log('nodeModel', nodeModel);
    // });
}

function loadLocalModel2(gltfUrl) {
    // 创建一个数据源用于管理所有模型（可自定义名称）
    const modelDataSource = new Cesium.GeoJsonDataSource('BuildingModels');

    // 将数据源添加到viewer
    viewer.dataSources.add(modelDataSource);

    // 加载GLTF的JSON数据
    Cesium.Resource.fetchJson(gltfUrl)
        .then(gltfJson => {
            console.log('gltfJson', gltfJson);

            // 遍历所有nodes
            gltfJson.nodes.forEach((node, index) => {
                // 检查bbox有效性
                const bbox = node.extras?.geometry?.bbox;
                if (!bbox || bbox.length !== 4) {
                    console.warn(`节点${index}缺少有效的bbox信息`);
                    return;
                }

                // 解析bbox并计算中心点
                const minLon = bbox[0];
                const minLat = bbox[1];
                const maxLon = bbox[2];
                const maxLat = bbox[3];
                const centerLon = (minLon + maxLon) / 2;
                const centerLat = (minLat + maxLat) / 2;
                const height = 0; // 从属性中获取高度

                // 创建模型对应的Entity
                const entity = new Cesium.Entity({
                    // 位置：中心点经纬度
                    position: Cesium.Cartesian3.fromDegrees(centerLon, centerLat, height),
                    // 模型属性：加载GLTF并应用位置
                    model: {
                        uri: gltfUrl, // 模型URL
                        nodeIndex: index, // 指定加载当前节点
                        // 模型矩阵：基于位置的局部坐标系（东-北-上）
                        modelMatrix: Cesium.Transforms.eastNorthUpToFixedFrame(
                            Cesium.Cartesian3.fromDegrees(centerLon, centerLat, height)
                        ),
                        // 可选：设置模型缩放、颜色等
                        scale: 1.0,
                        color: Cesium.Color.WHITE,
                    },
                    // 可选：绑定模型的属性信息（方便后续查询）
                    properties: node.extras?.properties || {},
                });

                // 将Entity添加到数据源
                modelDataSource.entities.add(entity);
            });
        })
        .catch(error => {
            console.error('加载GLTF JSON失败：', error);
        });
}

// 加载灯光
function loadLight() {
    const { scene, camera } = viewer;

    if (!scene.specularEnvironmentMapsSupported) {
        window.alert('This browser does not support specular environment maps.');
    }

    // const environmentMapURL =
    //     'https://cesium.com/public/SandcastleSampleData/kiara_6_afternoon_2k_ibl.ktx2';

    // // 定义球面谐波系数（用于环境光照计算）
    // // 注释说明：系数通过Google的Filament项目生成，提供了生成步骤
    // const L00 = new Cesium.Cartesian3(1.234897375106812, 1.221635103225708, 1.273374080657959);
    // const L1_1 = new Cesium.Cartesian3(1.136140108108521, 1.171419978141785, 1.287894368171692);
    // const L10 = new Cesium.Cartesian3(1.245410919189453, 1.245791077613831, 1.283067107200623);
    // const L11 = new Cesium.Cartesian3(1.107124328613281, 1.112697005271912, 1.153419137001038);
    // const L2_2 = new Cesium.Cartesian3(1.08641505241394, 1.079904079437256, 1.10212504863739);
    // const L2_1 = new Cesium.Cartesian3(1.190043210983276, 1.186099290847778, 1.214627981185913);
    // const L20 = new Cesium.Cartesian3(0.017783647403121, 0.020140396431088, 0.025317270308733);
    // const L21 = new Cesium.Cartesian3(1.087014317512512, 1.084779262542725, 1.111417651176453);
    // const L22 = new Cesium.Cartesian3(-0.052426788955927, -0.048315055668354, -0.041973855346441);
    // // 将所有球面谐波系数组合成数组
    // const coefficients = [L00, L1_1, L10, L11, L2_2, L2_1, L20, L21, L22];

    // // 创建基于图像的光照配置对象
    // const imageBasedLighting = new Cesium.ImageBasedLighting({
    //     sphericalHarmonicCoefficients: coefficients, // 球面谐波系数（用于漫反射）
    //     specularEnvironmentMaps: environmentMapURL, // 镜面环境贴图（用于镜面反射）
    // });

    // 光照
    options1.value = [
        {
            text: '太阳光',
            onselect: () => {
                viewer.scene.light = new Cesium.SunLight();
                const today = new Date();
                const targetTime = new Date(
                    today.getFullYear(),
                    today.getMonth(),
                    today.getDay(),
                    14,
                    0,
                    0
                );
                console.log('设置太阳位置');
                viewer.clock.currentTime = Cesium.JulianDate.fromDate(targetTime);
            },
        },
        {
            text: '固定方向光',
            onselect: () => {
                // 配置场景的方向光
                scene.light = new Cesium.DirectionalLight({
                    // 光源方向向量
                    direction: new Cesium.Cartesian3(
                        0.2454278300540191,
                        0.8842635425193919,
                        0.39729481195458805
                    ),
                    // 初始光强度设为0（后续可通过交互修改）
                    intensity: 10.0,
                });
            },
        },
        {
            text: '跟随镜头方向光',
            onselect: () => {
                // 配置场景的方向光
                scene.light = new Cesium.DirectionalLight({
                    direction: viewer.camera.direction, // 调整光源方向向量
                    // 初始光强度设为0（后续可通过交互修改）
                    intensity: 10.0,
                });
                // 添加事件监听器，使光源随摄像头移动
                viewer.camera.changed.addEventListener(function () {
                    viewer.scene.light.direction = viewer.camera.direction;
                });
            },
        },
        {
            text: 'IBL环境贴图光照',
            onselect: () => {
                imageBasedLighting.sphericalHarmonicCoefficients = coefficients;
                imageBasedLighting.specularEnvironmentMaps = environmentMapURL;
                imageBasedLighting.imageBasedLightingFactor = Cesium.Cartesian2.ONE; // 光照因子设为1（完全启用
                scene.light.intensity = 10.0;
            },
        },
        {
            text: '天空光',
            onselect: () => {
                imageBasedLighting.sphericalHarmonicCoefficients = undefined;
                imageBasedLighting.specularEnvironmentMaps = undefined;
                imageBasedLighting.imageBasedLightingFactor = Cesium.Cartesian2.ONE; // 光照因子设为1（完全启用
                scene.light.intensity = 2.0;
            },
        },
        {
            text: '无光照',
            onselect: () => {
                viewer.scene.light = undefined;
            },
        },
    ];
}

// 加载3dTiles
async function load3DTiles() {
    console.log('load3DTiles');
    const tileset = await Cesium.Cesium3DTileset.fromUrl('/d3tile1/buildType2023/tileset.json');
    // const tileset = await Cesium.Cesium3DTileset.fromUrl('/model/models (7)/tileset.json');
    console.log('tileset', tileset);
    // 添加到场景
    viewer.scene.primitives.add(tileset);
    // viewer.zoomTo(tileset);

    // tileset.initialTilesLoaded.addEventListener(function () {
    //     console.log('load',tileset.root );
    //     viewer.zoomTo(tileset)
    //     // viewer.camera.flyTo({
    //     //     destination: tileset.root.content.tile.children[0], // 目标包围球
    //     //     duration: 2, // 飞行持续时间（秒），可选
    //     //     complete: function () {
    //     //         console.log('已聚焦到模型包围盒');
    //     //     },
    //     // });
    // });

    options2.value = [
        // {
        //     text: '普通-动态光圈',
        //     onselect: () => {
        //         const customShader = new Cesium.CustomShader({
        //             //片元着色器
        //             fragmentShaderText: `
        //                 void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
        //                     vec3 positionMC = fsInput.attributes.positionMC;
        //                     material.diffuse = vec3(0.0, 1.0-positionMC.x*0.5, 1.0-positionMC.x*0.0015);

        //                     float _baseHeight = 0.0; // 物体的基础高度，需要修改成一个合适的建筑基础高度
        //                     float _heightRange = 20.0; // 高亮的范围(_baseHeight ~ _baseHeight + _heightRange) 默认是 0-60米
        //                     float _glowRange = 20.0; // 光环的移动范围(高度)

        //                     float vtxf_height = fsInput.attributes.positionMC.y - _baseHeight;
        //                     float vtxf_a11 = fract(czm_frameNumber / 360.0) * 3.14159265 * 2.0; //此处括号内分母为移动速度
        //                     float vtxf_a12 = vtxf_height / _heightRange + sin(vtxf_a11) * 0.1;
        //                     material.diffuse *= vec3(vtxf_a12, vtxf_a12, vtxf_a12);

        //                     float vtxf_a13 = fract(czm_frameNumber / 360.0); //此处括号内分母为移动速度，数值越大，速度越慢
        //                     float vtxf_h = clamp(vtxf_height / _glowRange, 0.0, 1.0);
        //                     vtxf_a13 = abs(vtxf_a13 - 0.5) * 2.0;
        //                     float vtxf_diff = step(0.01, abs(vtxf_h - vtxf_a13)); // 0.1 为高亮光条的范围（粗细）
        //                     material.diffuse += material.diffuse * (1.0 - vtxf_diff);
        //                 }`,
        //         });

        //         tileset.customShader = customShader;
        //     },
        // },
        {
            text: 'PBR-基本颜色',
            onselect: () => {
                const customShader1 = new Cesium.CustomShader({
                    lightingModel: Cesium.LightingModel.PBR,
                    translucent: true, // 默认为 false，开启后 alpha 才生效
                    fragmentShaderText: `
                    void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
                    // 设置基础颜色
                    // material.diffuse = vec3(0.2, 0.6, 0.9) ;
                    // material.diffuse = vec3(0.4863, 0.8941, 0.9922);

                    material.diffuse = vec3(0.0392, 0.2196, 0.5686) * vec3(2,2,2);
                    // material.emissive = vec3(0.05, 0.05, 0.1);
                    }
                `,
                });
                tileset.customShader = customShader1;
            },
        },
        {
            text: 'PBR-修改材质透明度相关',
            onselect: () => {
                const customShader = new Cesium.CustomShader({
                    lightingModel: Cesium.LightingModel.PBR,
                    uniforms: {
                        u_metallic: {
                            type: Cesium.UniformType.FLOAT,
                            value: 1.0,
                        },
                        u_roughness: {
                            type: Cesium.UniformType.FLOAT,
                            value: 0.2,
                        },
                        u_brightness: {
                            type: Cesium.UniformType.FLOAT,
                            value: 1.3,
                        },
                    },
                    fragmentShaderText: `
                        void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material)
                        {
                        // 设置纯白色基础色，并应用亮度
                        material.diffuse = vec3(0.8, 0.8, 0.8) * u_brightness;
                        
                        // 设置高镜面反射，模拟金属质感
                        material.specular = vec3(u_metallic);
                        
                        // 设置低粗糙度，增加反光效果
                        material.roughness = u_roughness;
                        
                        // 保持完全不透明
                        material.alpha = 1.0;


                        }
                    `,
                });
                tileset.customShader = customShader;
            },
        },
        {
            text: '非PBR-修改材质透明度相关',
            onselect: () => {
                const customShader = new Cesium.CustomShader({
                    // lightingModel: Cesium.LightingModel.LAM,
                    uniforms: {
                        u_metallic: {
                            type: Cesium.UniformType.FLOAT,
                            value: 0.95,
                        },
                        u_roughness: {
                            type: Cesium.UniformType.FLOAT,
                            value: 0.0,
                        },
                        u_brightness: {
                            type: Cesium.UniformType.FLOAT,
                            value: 1.3,
                        },
                    },
                    fragmentShaderText: `
                        void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material)
                        {
                        // 设置纯白色基础色，并应用亮度
                        material.diffuse = vec3(1.0, 1.0, 1.0) * u_brightness;
                        
                        // 保持完全不透明
                        material.alpha = 1.0;
                        }
                    `,
                });
                tileset.customShader = customShader;
            },
        },
        {
            text: 'PBR-贴图',
            onselect: () => {
                const customShader = new Cesium.CustomShader({
                    lightingModel: Cesium.LightingModel.PBR,
                    uniforms: {
                        u_metallic: {
                            type: Cesium.UniformType.FLOAT,
                            value: 0.95,
                        },
                        u_roughness: {
                            type: Cesium.UniformType.FLOAT,
                            value: 0.0,
                        },
                        u_brightness: {
                            type: Cesium.UniformType.FLOAT,
                            value: 1.3,
                        },
                        u_texture: {
                            value: new Cesium.TextureUniform({
                                url: '/cesiumData/images/js2.jpg',
                            }),
                            type: Cesium.UniformType.SAMPLER_2D,
                        },
                        u_texture1: {
                            value: new Cesium.TextureUniform({
                                url: '/cesiumData/images/js2.jpg',
                            }),
                            type: Cesium.UniformType.SAMPLER_2D,
                        },
                    },
                    //设置变量，由顶点着色器传递给片元着色器
                    varyings: {
                        v_normalMC: Cesium.VaryingType.VEC3,
                        v_st: Cesium.VaryingType.VEC3,
                    },
                    //将法向量从顶点着色器设置变量传给片元着色器
                    vertexShaderText: `
                    void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) {
                            v_normalMC = vsInput.attributes.normalMC;
                            v_st=vsInput.attributes.positionMC ;   
                }`,
                    fragmentShaderText: `
                    void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
                                        vec3 positionMC = fsInput.attributes.positionMC;
                                        //这里是设置要贴图的图片的尺寸，设置小了会重复
                                        float width = 10.0;
                                        float height = 20.0;
                                        vec3 rgb;
                                        //这是是设置了屋顶的颜色，当和法向量平行时，就是屋顶，这里设置0.95，相当于垂直，建筑物四周开始贴图
                                        if (dot(vec3(0.0, 1.0, 0.0), v_normalMC) > 0.95) {
                                            material.diffuse = vec3(0.65, 0.65, 0.65);
                                        } else {
                                            float textureX = 0.0;
                                            float dotYAxis = dot(vec3(0.0, 0.0, 1.0), v_normalMC);
                                            // cos(45deg) 约等于 0.71，这里是建筑物四周的向量与法向量会大于四十五度夹角
                                            if (dotYAxis > 0.71 || dotYAxis < -0.71) {
                                            //x代表的是前后面
                                                textureX = mod(positionMC.x, width) / width;
                                            } else {
                                            //z代表的是左右面
                                                textureX = mod(positionMC.z, width) / width;
                                            }
                                            float textureY = mod(positionMC.y, height) / height;
                                            //我这里是根据建筑物高度贴了两张不同的图片
                                            if (positionMC.y > 40.0) {
                                                rgb = texture(u_texture, vec2(textureX, textureY)).rgb;       
                                            } else {
                                                rgb = texture(u_texture1, vec2(textureX, textureY)).rgb;
                                            }
                                            
                                            material.diffuse = rgb;
                                        }
                                    }`,
                });
                tileset.customShader = customShader;
            },
        },
        {
            text: 'PBR-贴图+叠加底色',
            onselect: () => {
                const customShader = new Cesium.CustomShader({
                    lightingModel: Cesium.LightingModel.PBR,
                    uniforms: {
                        u_metallic: {
                            type: Cesium.UniformType.FLOAT,
                            value: 0.95,
                        },
                        u_roughness: {
                            type: Cesium.UniformType.FLOAT,
                            value: 0.0,
                        },
                        u_brightness: {
                            type: Cesium.UniformType.FLOAT,
                            value: 1.3,
                        },
                        u_texture: {
                            value: new Cesium.TextureUniform({
                                url: '/cesiumData/images/js2.jpg',
                            }),
                            type: Cesium.UniformType.SAMPLER_2D,
                        },
                        u_texture1: {
                            value: new Cesium.TextureUniform({
                                url: '/cesiumData/images/js2.jpg',
                            }),
                            type: Cesium.UniformType.SAMPLER_2D,
                        },
                    },
                    //设置变量，由顶点着色器传递给片元着色器
                    varyings: {
                        v_normalMC: Cesium.VaryingType.VEC3,
                        v_st: Cesium.VaryingType.VEC3,
                    },
                    //将法向量从顶点着色器设置变量传给片元着色器
                    vertexShaderText: `
                    void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) {
                            v_normalMC = vsInput.attributes.normalMC;
                            v_st=vsInput.attributes.positionMC ;   
                }`,
                    fragmentShaderText: `
                    void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
                                        vec3 positionMC = fsInput.attributes.positionMC;
                                        //这里是设置要贴图的图片的尺寸，设置小了会重复
                                        float width = 10.0;
                                        float height = 20.0;
                                        float light = 3.0 ;
                                        vec3 rgb;
                                        //这是是设置了屋顶的颜色，当和法向量平行时，就是屋顶，这里设置0.95，相当于垂直，建筑物四周开始贴图
                                        if (dot(vec3(0.0, 1.0, 0.0), v_normalMC) > 0.95) {
                                            material.diffuse = vec3(0.65, 0.65, 0.65);
                                        } else {
                                            float textureX = 0.0;
                                            float dotYAxis = dot(vec3(0.0, 0.0, 1.0), v_normalMC);
                                            // cos(45deg) 约等于 0.71，这里是建筑物四周的向量与法向量会大于四十五度夹角
                                            if (dotYAxis > 0.71 || dotYAxis < -0.71) {
                                            //x代表的是前后面
                                                textureX = mod(positionMC.x, width) / width;
                                            } else {
                                            //z代表的是左右面
                                                textureX = mod(positionMC.z, width) / width;
                                            }
                                            float textureY = mod(positionMC.y, height) / height;
                                            //我这里是根据建筑物高度贴了两张不同的图片
                                            if (positionMC.y > 40.0) {
                                                rgb = texture(u_texture, vec2(textureX, textureY)).rgb;       
                                            } else {
                                                rgb = texture(u_texture1, vec2(textureX, textureY)).rgb;
                                            }
                                            
                                            material.diffuse = rgb*vec3(0.0392, 0.2196, 0.5686) * light;
                                        }
                                    }`,
                });
                tileset.customShader = customShader;
            },
        },

        {
            text: 'PBR-贴图+叠加底色+金属反光',
            onselect: () => {
                const customShader = new Cesium.CustomShader({
                    lightingModel: Cesium.LightingModel.PBR,
                    uniforms: {
                        u_metallic: {
                            type: Cesium.UniformType.FLOAT,
                            value: 0.95, // 金属度：0.0-非金属，1.0-纯金属
                        },
                        u_roughness: {
                            type: Cesium.UniformType.FLOAT,
                            value: 0.3, // 粗糙度：0.0-极光滑(镜面)，1.0-极粗糙
                        },
                        u_brightness: {
                            type: Cesium.UniformType.FLOAT,
                            value: 1.3,
                        },
                        u_texture: {
                            value: new Cesium.TextureUniform({
                                url: '/cesiumData/images/js2.jpg',
                            }),
                            type: Cesium.UniformType.SAMPLER_2D,
                        },
                        u_texture1: {
                            value: new Cesium.TextureUniform({
                                url: '/cesiumData/images/js2.jpg',
                            }),
                            type: Cesium.UniformType.SAMPLER_2D,
                        },
                    },
                    varyings: {
                        v_normalMC: Cesium.VaryingType.VEC3,
                        v_st: Cesium.VaryingType.VEC3,
                    },
                    vertexShaderText: `
            void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) {
                    v_normalMC = vsInput.attributes.normalMC;
                    v_st = vsInput.attributes.positionMC;   
            }`,
                    fragmentShaderText: `
            void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
                                vec3 positionMC = fsInput.attributes.positionMC;
                                float width = 10.0;
                                float height = 20.0;
                                vec3 rgb;
                                
                                // 屋顶处理
                                if (dot(vec3(0.0, 1.0, 0.0), v_normalMC) > 0.95) {
                                    material.diffuse = vec3(0.65, 0.65, 0.65);
                                    // 屋顶也添加金属质感
                                    // material.metallic = 0.3; // 屋顶金属度降低
                                    // material.roughness = 0.5; // 屋顶更粗糙
                                } else {
                                    float textureX = 0.0;
                                    float dotYAxis = dot(vec3(0.0, 0.0, 1.0), v_normalMC);
                                    
                                    if (dotYAxis > 0.71 || dotYAxis < -0.71) {
                                        textureX = mod(positionMC.x, width) / width;
                                    } else {
                                        textureX = mod(positionMC.z, width) / width;
                                    }
                                    
                                    float textureY = mod(positionMC.y, height) / height;
                                    
                                    // 根据高度选择纹理
                                    if (positionMC.y > 40.0) {
                                        rgb = texture(u_texture, vec2(textureX, textureY)).rgb;       
                                    } else {
                                        rgb = texture(u_texture1, vec2(textureX, textureY)).rgb;
                                    }
                                    
                                    // 应用基础颜色和亮度
                                    material.diffuse = rgb * vec3(0.0392, 0.2196, 0.5686) * u_brightness;
                                    
                                    // 核心：设置金属反光属性
                                  
                                    // 设置高镜面反射，模拟金属质感
                                    material.specular = vec3(u_metallic);
                        
                                    // 设置低粗糙度，增加反光效果
                                    material.roughness = u_roughness;

                                    material.specular = vec3(0.9, 0.95, 1.0);  // 高光颜色
                                }
                                
                                // 可选：添加环境反射增强金属感
                                material.occlusion = 1.0; // 环境光遮蔽，1.0表示无遮蔽
                                material.emissive = vec3(0.02); // 轻微自发光增强金属光泽
                            }`,
                });
                tileset.customShader = customShader;
            },
        },
    ];
}

// 加载底图
function loadLayer() {
    return new Promise(async (resolve, reject) => {
        try {
            viewer.imageryLayers.addImageryProvider(
                new Cesium.WebMapTileServiceImageryProvider({
                    //todo 内网部署时地图切换
                    url: 'http://10.64.142.2:8081/geoserver/gwc/service/wmts',
                    layer: 'map_night_google',
                    format: 'image/png',
                    tileMatrixSetID: 'EPSG:3857_map_night_google',
                    // maximumLevel: 11, // 与URL中的缩放级别（11）匹配
                    style: '',
                    tileHeight: 256,
                    tileWidth: 256,
                    // 坐标系配置（EPSG:3857）
                    coordinateSystem: Cesium.Cartesian3.WGS84,
                    // 从 XML 提取的边界范围（经纬度）
                    rectangle: Cesium.Rectangle.fromDegrees(
                        113.69555650336041,
                        29.97112166680848,
                        115.07572488257945,
                        31.36078841097098
                    ),
                    tileMatrixLabels: [
                        'EPSG:3857_map_night_google:0',
                        'EPSG:3857_map_night_google:1',
                        'EPSG:3857_map_night_google:2',
                        'EPSG:3857_map_night_google:3',
                        'EPSG:3857_map_night_google:4',
                        'EPSG:3857_map_night_google:5',
                        'EPSG:3857_map_night_google:6',
                        'EPSG:3857_map_night_google:7',
                        'EPSG:3857_map_night_google:8',
                        'EPSG:3857_map_night_google:9',
                        'EPSG:3857_map_night_google:10',
                        'EPSG:3857_map_night_google:11',
                        'EPSG:3857_map_night_google:12',
                        'EPSG:3857_map_night_google:13',
                        'EPSG:3857_map_night_google:14',
                        'EPSG:3857_map_night_google:15',
                        'EPSG:3857_map_night_google:16',
                        'EPSG:3857_map_night_google:17',
                        'EPSG:3857_map_night_google:18',
                    ],
                })
            );

            resolve();
        } catch (e) {
            // reject(e);
            console.error(e);
            resolve();
        }
    });
}
</script>

<style scoped lang="scss">
.page-container {
    width: 100%;
    height: 100%;
    position: relative;
    .tool-box {
        display: flex;
        align-items: center;
        gap: 20px;
    }
}
#cesiumContainer {
    width: 100%;
    height: 100%;
}
</style>
